const qId = (x) => document.getElementById(x)
const qEClass = (t, c) => t.querySelector(c)
const note_t = qId('note-t')
const addBtn = qId('add')
const main = document.querySelector(".main")
const notes=JSON.parse(localStorage.getItem("texts")) || []

window.onload = () => {
    notes.forEach((text) => {
        addNewNote(text)
    })
}
    

addBtn.addEventListener('click', () => {
    addNewNote()
})
function addNewNote(text = '') {
    let note = qId("note-t").content
    let clone = document.importNode(note, true)

    let textarea = clone.getElementById("textarea")
    let main = clone.querySelector(".main")
    main.innerText = text
    textarea.value = text
  
    if(text.length > 0){
        main.classList.toggle("hidden")
        textarea.classList.toggle("hidden")
    }


    clone.querySelector(".delete").addEventListener('click', (e) => {
        e.currentTarget.parentNode.parentNode.remove()
        updateText()
    })
    clone.querySelector(".edit").addEventListener('click', (e) => {
        // console.log(clone.querySelector(".main"))
        main.classList.toggle("hidden")
        textarea.classList.toggle("hidden")
    })
    textarea.addEventListener('input', (e) => {
        const { value } = e.target
        main.innerHTML = marked.parse(value)
        updateText(value)
    })
    document.body.appendChild(clone)
    localStorage.setItem("markCount", localStorage.getItem("markCount")  + 1)

}


function updateText() {
    let areas=document.querySelectorAll("textarea");
    const notes=[]
    areas.forEach((x) => {
        notes.push(x.value)
    })
    if (window.saveHandle) {
        clearTimeout(window.saveHandle)
        window.saveHandle = setTimeout(() => {
            localStorage.setItem("texts", JSON.stringify(notes))
        }, 300)
    }else {
        window.saveHandle = setTimeout(() => {
            localStorage.setItem("texts", JSON.stringify(notes))
        }, 300)
    }
}